// import _local from "../../cache/_local";
import _regular from "../../../utils/_regular";
import _object from "../../../utils/_object";
import lib_activity from "../../../api/lib_activity";
import lib_city from "../../../api/lib_city";
import _layer from "../../../common/_layer";
import _time from "../../../utils/_time"
import lib_car from "../../../api/lib_car";
import swiperData from "../../../common/_swiperdata";
import lib_clue from "../../../api/lib_clue";
import _report from "../../../common/_report"
import lib_tiktok from "../../../api/lib_tiktok";


Page({
  data: {
    /**页面参数 */
    activity_id: '', //活动ID
    channel: 3, //渠道
    tids: 0, // 模板ID

    /**项目信息 */

    custom_car: 0, // 是否自定义车型库
    tid: 0, // 有无车型库
    share_theme: '', //分享描述
    stime: 0, // 项目开始时间
    etime: 0, // 项目结束时间
    ui: {
      head: '', //头图
      tail: '', //详情图
      share: '', //分享图
      bg_color: '', //表单背景色
      font_color: '', //文本颜色
      btn_bg_color: '', //按钮背景色
      btn_font_color: '', //按钮文本颜色
      btn_text: '', //按钮文本值
      btm_btn_text: '', //底部按钮文本
      is_banner: 0, //是否有轮播图
      is_counter: 0, //是否有倒计时
      is_copyright: 1, //协议
      jmp_url: 0, //0-报名成功;1-帮朋友报名;2-置换二手车;3-邮寄门票
    },

    /**form表单 */
    city: '', //城市
    brand_name: '', //品牌名称
    series_name: '', // 车型名称
    brand: '', //品牌+车型
    name: '', // 姓名
    phone: '', //电话
    location: '', //

    //城市联级选择
    citys: [], //城市数据

    is_dialog_car: false, //车型弹框
    is_dialog_city: false, //城市弹框
    brand_show: true, //品牌content
    series_show: false, //车型content

    is_city: false, //表单城市项，默认无城市
    is_stop: false, //活动是否已结束


    /**车型相关 */
    hot: [], //热门车型
    brand_list: [], //品牌
    letter: [], //右侧ABC
    series_list: [], //车型

    brand_id: undefined, //品牌id
    series_id: undefined, //车型id

    current_letter: 'A',
    toView: '', // 左侧滚动
    currSeries: '',


    /**城市相关 */
    currIndexCity: -1,
    currProvince: '',
    currCity: '',

    swiper_list: [], //轮播
    innerHeight: 827,
    clickid: '',
  },

  onLoad: function (options) {
    console.log(options, 'options');


    //项目ID参数
    if (_object._length(options) > 0 && options.hasOwnProperty('tids') && options.tids > 0) {
      //设置项目缓存
      this.setData({
        tids: options.tids
      })
    } else {
      this.setData({
        tids: 651
      })
    }

    if (_object._length(options) > 0 && options.hasOwnProperty('activity_id') && options.activity_id > 0) {
      //设置项目缓存
      this.setData({
        activity_id: options.activity_id
      })
    } else {
      this.setData({
        activity_id: 775
      })
    }

    if (_object._length(options) > 0 && options.hasOwnProperty('clickid')) {
      //设置项目缓存
      this.setData({
        clickid: options.clickid
      })
    }

  },
  onShow() {
    this.setData({ swiper_list: swiperData.address_swiper });

    this.init_info();

    // tt.getSystemInfo({
    //   success: (res) => {
    //     this.setData({
    //       innerHeight: res.windowHeight
    //     });
    //   },
    //   fail: (res) => {
    //     this.setData({ innerHeight: 827 })
    //     console.log(res);
    //   },
    // });
  },
  onReady() {
    try {
      const res = tt.getSystemInfoSync();
      this.setData({
        innerHeight: res.windowHeight
      });
    } catch (err) {
      this.setData({ innerHeight: 827 })
      console.log('getSystemInfoSync Error: ', err);
    }
  },

  // 项目信息
  init_info() {
    const { activity_id, tids, custom_car } = this.data
    lib_activity.info(activity_id, tids).then((res) => {
      if (res.code != 0) {
        _layer.message(res.msg);
        return;
      }

      let data = res.data
      // console.log(data, '====');
      this.setData({
        share_theme: data.activity.share_theme,
        etime: data.activity.etime,
        stime: data.activity.stime,
        tid: data.activity.tid,
        custom_car: data.activity.custom_car
      })
      if (data.ui == null) {
        this.setData({ ui: {} })
        return;
      }
      this.setData({ ui: data.ui })

      // 项目结束
      if (!data.activity.state || (_time._current() > data.activity.etime)) {
        this.setData({
          is_stop: true
        })
        return;
      }

      // 判断是否有城市
      let city = []
      if (data.activity.city) {
        city = data.activity.city.split(',');
      }
      if (city.length == 1 && city[0] > 0) {
        //单城市项目
        this.setData({
          is_city: false
        })
      } else {
        //多城市项目
        this.setData({
          is_city: true
        })
        this.getCity(data.activity.city)
      }

      this.init_car(activity_id, custom_car);


    })
  },

  // 城市
  getCity(city) {
    lib_city.list(city).then(res => {
      if (res.code != 0) {
        _layer.message(res.msg);
        return;
      }
      this.setData({ citys: res.data })
    })
  },

  //车型
  init_car(activity_id, custom_car) {
    lib_car.brand(activity_id, custom_car).then(res => {
      if (res.code != 0) {
        _layer.message(res.msg);
        return;
      }
      this.setData({
        hot: res.data.hot,
        brand_list: res.data.brand,
        letter: res.data.letter,
      })
    })
  },


  /**methods */
  // 城市methods
  ChangeCity() {
    this.setData({ is_dialog_city: !this.data.is_dialog_city })
  },
  ChangeCityStop() {
    this.setData({ is_dialog_city: true })
  },
  ChangeCityFlagS() {
    this.setData({ is_dialog_city: !this.data.is_dialog_city })
  },
  clkProvince(e) {
    const { index, item } = e.currentTarget.dataset
    this.setData({
      currIndexCity: index,
      currProvince: item.name
    })
  },
  clkCity(e) {
    this.setData({ currCity: e.currentTarget.dataset.item });
    setTimeout(() => {
      this.setData({
        is_dialog_city: false,
        city: this.data.currCity,
        location: this.data.currProvince + '+' + this.data.currCity
      });
    }, 4);
  },

  // 车型methods
  ChangeBrandFlag(e) {
    this.setData({
      is_dialog_car: !this.data.is_dialog_car,
      brand_show: true,
      series_show: false
    });
  },
  ChangeBrandStop() {
    this.setData({ is_dialog_car: true });
  },
  //字母
  clk_letter(e) {
    this.setData({
      current_letter: e.currentTarget.dataset.item,
      toView: e.currentTarget.dataset.item,
    })
  },
  //品牌
  clk_brand(e) {
    const { brand_id, brand_name } = e.currentTarget.dataset.item
    this.setData({
      brand_id: brand_id,
      brand_show: false,
      series_show: true,
      brand_name: brand_name
    })
    // 请求车型
    const { activity_id, custom_car } = this.data
    lib_car.series(activity_id, custom_car, brand_id).then(res => {
      if (res.code != 0) {
        _layer.message(res.msg);
        return;
      }
      this.setData({
        series_list: res.data
      })
    })
  },
  //车型
  clk_series(e) {
    const { name } = e.currentTarget.dataset.item
    this.setData({
      brand: this.data.brand_name + '/' + name,
      series_name: name
    })
    setTimeout(() => {
      this.setData({
        is_dialog_car: false
      })
    }, 4)
  },
  //返回
  goback() {
    this.setData({
      series_show: false,
      brand_show: true
    })
  },

  //获取本机手机号
  getPhoneNumber(e) {
    if (e.detail.errMsg == 'getPhoneNumber:ok') {
      const iv = e.detail.iv;
      const encryptedData = e.detail.encryptedData;
      lib_tiktok.phone(encryptedData, iv).then((res) => {
        if (res.code == 0) {
          this.setData({ phone: res.data.phone })

        } else {
          _layer.message(res.msg)
        }
      })

    }


  },


  ChangePhone(e) {
    this.setData({ phone: e.detail });
  },
  ChangeName(e) {
    this.setData({ name: e.detail });
  },

  //用户授权
  userSetting() {
    let that = this;
    tt.getSetting({
      success: (res) => {
        let authSetting = res.authSetting
        if (authSetting['scope.userLocation']) {
          // 已授权
        } else {
          tt.showModal({
            title: '您未开启地理位置授权',
            content: '前往开启系统地理定位',
            success: res => {
              if (res.confirm) {
                tt.openSetting({
                  success: (result) => {
                    that.getLocation()
                  },
                });
              }
            }
          })
        }
      },
      fail: (res) => {
        console.log(res, '+++');
      },
    });
  },
  getLocation() {
    tt.getLocation({
      success: (res) => {
        if (res.errMsg == 'getLocation:ok') {
          this.data.citys.forEach((item, index) => {
            item.children.forEach((it, id) => {
              if (it.name == res.city) {
                this.setData({
                  city: res.city,
                  location: item.name + '+' + res.city
                })
              }
            })
          })
        }
      },
      fail: (err) => {
        this.userSetting()
        console.log(err);
      },
    });
  },
  //获取定位城市
  get_localCity() {
    this.getLocation()
  },
  // 表单提交
  submit() {
    if (!this.data.name) {
      tt.showToast({
        title: '请输入姓名',
        icon: 'none'
      });
      return;
    }

    if (!this.data.phone) {
      tt.showToast({
        title: '请输入手机号',
        icon: 'none'
      });
      return;
    }
    if (!_regular.is_mobile(this.data.phone)) {
      tt.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }

    if (!this.data.brand) {
      tt.showToast({
        title: '请选择品牌车系',
        icon: 'none'
      });
      return;
    }

    if (!this.data.city) {
      tt.showToast({
        title: '请选择城市',
        icon: 'none'
      });
      return;
    }

    // 报名
    // let location = this.data.is_city ? (this.data.currProvince + '+' + this.data.currCity) : '';
    let form_ui_id = this.data.ui.hasOwnProperty("id") ? this.data.ui.id : 0;

    let pages = getCurrentPages(); // 获取页面指针数组
    let currentPage = pages[pages.length - 1]; // 获取当前页
    let route = currentPage.route;

    let { activity_id, tids } = currentPage.options;
    let url = `${route}?activity_id=${activity_id}&tids=${tids}`

    let params = {
      activity_id: this.data.activity_id,
      channel_code: this.data.channel,
      location: this.data.location,
      url,
      form_name: this.data.name,
      form_phone: this.data.phone,
      form_brand: this.data.brand_name,
      form_series: this.data.series_name,
      form_ui_id,
    }
    console.log(params, '入参');

    lib_clue.receive(params).then(res => {
      console.log(res, '报名结果');
      if (res.code != 0) {
        _layer.message(res.msg);
        return;
      }

      _layer.message('报名成功！')
      //监测
      _report._post(this.data.clickid)

      //缓存当页面链接
      // cache_url.set(url)
      //跳转
      const jmp_url = _object._length(this.data.ui) > 0 ? this.data.ui.jmp_url : 0
      //跳转地址
      // const url = lib_success.jmp_url(jmp_url)
      tt.navigateTo({
        url: `/pages/success/success?id=${res.data.id}`,
      });
    })
  },

  //分享
  async onShareAppMessage(option) {
    return {
      title: this.data.ui.share_theme,
      path: `pages/autoshow/autoshow?activity_id=${this.data.activity_id}&tids=${this.data.tids}`, // ?后面的参数会在转发页面打开时传入onLoad方法
      imageUrl: this.data.ui.share, // 支持本地或远程图片，默认是小程序 icon
      success(res) {
        console.log('分享成功', res);
      },
      fail() {
        console.log("转发发布器调起失败");
      },
    };
  },

});